package tpoperativa.servlet;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.log4j.Logger;

public class ConnectionProvider {
	private static ConnectionProvider instance;

	private static final Logger LOGGER = Logger.getLogger(ConnectionProvider.class);

	private Connection connection=null;

	public ConnectionProvider(){
		try {
			Class.forName("org.apache.derby.jdbc.ClientDriver");
		} catch (ClassNotFoundException e) {
			LOGGER.error("Error al cargar los Drivers de Coneccion a Derby",e);
		}   
	}

	public static ConnectionProvider getInstance()
	{
		if (instance==null)
			instance=new ConnectionProvider();
		return instance;
	}

	public Connection getConnection(String derbyURL, String userName, String password) throws SQLException
	{
		if(connection==null || (connection!=null && connection.isClosed())){
			connection=DriverManager.getConnection(derbyURL, userName, password);
			LOGGER.debug("Nueva Conexion");
		}
		return connection; 
	}

	public void closeConnection(){
		try {
			if(connection!=null &&  !connection.isClosed()){
				connection.close();

				/*
				 * Para forzar el cierre del driver
				 * DriverManager.getConnection("jdbc:derby:;shutdown=true");
				 */
				connection=null;
			}
		} catch (SQLException e) {
		}
	}
}
